package com.university.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.university.evaluation.entity.Appeal;
import com.university.evaluation.entity.StudentScoreDetail;
import com.university.evaluation.mapper.AppealMapper;
import com.university.evaluation.service.AppealService;
import com.university.evaluation.service.StudentScoreDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppealServiceImpl extends ServiceImpl<AppealMapper, Appeal> implements AppealService {

    @Autowired
    private AppealMapper appealMapper;
    
    @Autowired
    private StudentScoreDetailService studentScoreDetailService;

    @Override
    public List<Appeal> findByStudentId(Long studentId) {
        return appealMapper.findByStudentId(studentId);
    }

    @Override
    public List<Appeal> findByStatus(String status) {
        // 将字符串状态转换为整数
        Integer statusInt = null;
        if (status != null) {
            try {
                statusInt = Integer.parseInt(status);
            } catch (NumberFormatException e) {
                // 处理异常，这里可以根据需要添加日志
            }
        }
        return appealMapper.findByStatus(statusInt);
    }

    @Override
    public Appeal findByScoreDetailId(Long scoreDetailId) {
        List<Appeal> appeals = appealMapper.findByScoreDetailId(scoreDetailId);
        if (appeals != null && !appeals.isEmpty()) {
            return appeals.get(0); // 返回第一个匹配的申诉
        }
        return null;
    }

    @Override
    public Appeal submitAppeal(Appeal appeal) {
        appeal.setStatus(0); // 0表示待处理
        appeal.setCreateTime(LocalDateTime.now());
        boolean saved = save(appeal);
        if (saved) {
            return getById(appeal.getId()); // 返回保存后的申诉对象
        }
        return null;
    }

    @Override
    public boolean processAppeal(Long appealId, String status, String remark, Double newScore) {
        Appeal appeal = getById(appealId);
        if (appeal != null) {
            // 将字符串状态转换为整数
            Integer statusInt = null;
            try {
                statusInt = Integer.parseInt(status);
            } catch (NumberFormatException e) {
                // 处理异常，这里可以根据需要添加日志
                return false;
            }
            
            appeal.setStatus(statusInt);
            appeal.setProcessResult(remark);
            // 这里可以从SecurityContext获取当前登录的管理员ID
            // appeal.setProcessBy(processorId);
            appeal.setProcessTime(LocalDateTime.now());
            
            // 如果申诉被通过且有新分数，则更新学生成绩
            if (statusInt == 1 && newScore != null) {
                StudentScoreDetail scoreDetail = studentScoreDetailService.getById(appeal.getScoreDetailId());
                if (scoreDetail != null) {
                    // 直接更新分数和状态，不使用updateScore方法（因为它会将状态设置为待审核）
                    scoreDetail.setScore(new BigDecimal(newScore));
                    scoreDetail.setStatus(1); // 直接设置为已通过状态
                    scoreDetail.setUpdateTime(LocalDateTime.now());
                    studentScoreDetailService.updateById(scoreDetail);
                }
            }
            
            return updateById(appeal);
        }
        return false;
    }

    @Override
    public Long countPendingAppeals() {
        QueryWrapper<Appeal> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0); // 0表示待处理
        return count(wrapper);
    }

    @Override
    public Map<String, Object> findByPage(Integer page, Integer pageSize, String status, Long studentId) {
        QueryWrapper<Appeal> wrapper = new QueryWrapper<>();
        
        // 将字符串状态转换为整数
        if (status != null) {
            try {
                Integer statusInt = Integer.parseInt(status);
                wrapper.eq("status", statusInt);
            } catch (NumberFormatException e) {
                // 处理异常，这里可以根据需要添加日志
            }
        }
        
        // 按学生ID筛选
        if (studentId != null) {
            wrapper.eq("student_id", studentId);
        }
        
        wrapper.orderByDesc("create_time");
        
        Page<Appeal> pageResult = new Page<>(page, pageSize);
        page(pageResult, wrapper);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("pages", pageResult.getPages());
        
        return result;
    }

}